package com.dempsey.gateway.filter;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.dempsey.common.core.utils.ServletUtils;
import com.dempsey.common.redis.service.RedisService;
import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Dempsey
 * Date 2022/5/24
 * Description
 */

@Component
public class RandomPathCheckFilter extends AbstractGatewayFilterFactory<RandomPathCheckFilter.Config> {

    private final static Log log = LogFactory.get();

    @Autowired
    private RedisService redisService;

    public RandomPathCheckFilter() {
        super(RandomPathCheckFilter.Config.class);
    }

    @Override
    public String name() {
        return "RandomPathCheck";
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {

            String path = exchange.getRequest().getPath().toString();
            if (!path.endsWith("createSeckillOrder")){
                return chain.filter(exchange);
            }

            String seckillStr = exchange.getRequest().getQueryParams().getFirst(config.paramName);
            log.info("过滤器捕捉秒杀访问请求，请求携带的随机字符串为: " + seckillStr);

            // DempseyTODO 2022/5/24 5:34 要从redis中拿哦
            String goodId = exchange.getRequest().getQueryParams().getFirst("goodId");
            String str = redisService.getCacheObject("seckill-acticity:" + goodId);
            log.info("过滤器捕捉秒杀访问请求，缓存中的随机字符串为: " + str);

            if (str.equals(seckillStr)) {
                return chain.filter(exchange);
            }

            return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "不在秒杀时间段内，请刷新页面");
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Lists.newArrayList("paramName");
    }

    @Data
    public static class Config {
        private String paramName;
    }

}
